﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<link href="js-console.css" rel="stylesheet" />
	<script src="string-extensions.js"></script>
	<!-- 4. You are given a text. Write a function that changes the text in all regions:
			* <upcase>text</upcase> to uppercase.
			* <lowcase>text</lowcase> to lowercase
			* <mixcase>text</mixcase> to mix casing(random)

		We are <mixcase>living</mixcase> in a <upcase>yellow 
		submarine</upcase>. We <mixcase>don't</mixcase> have 
		<lowcase>anything</lowcase> else.

		The expected result: We are LiVinG in a YELLOW SUBMARINE. We dOn'T have anything else.
		
		*Regions can be nested -->
	<style>
		textarea, button {
			display: block;
			width: 800px;
		}
	</style>
</head>
<body>
	<textarea id="input" placeholder='Enter text with tags ("upcase", "lowcase", "mixcase") to change'></textarea>
	<button onclick="doChange()">Change Text</button>
	<div id="js-console"></div>
	<script src="js-console.js"></script>
	<script>
		// New property in String class
		String.prototype.toMixCase = function () {
			if (this.length > 0) {
				var arr = new Array();

				for (var i = 0; i < this.length; i++) {
					var rand = Math.floor(Math.random() * 2)
					arr[i] = (rand == 1 ? this[i].toUpperCase() : this[i].toLowerCase());
				}

				return arr.join('').toString();
			}
		}

		function changeText(input) {
			var str = new String(input);

			if (str.length > 0) {
				var words = new Array("upcase", "lowcase", "mixcase");
				for (var i in words) {
					str = manageKeyword(str, words[i]);
				}
			}

			return str;
		}

		function manageKeyword(str, word) {
			var res = new Array();
			var keyword = "<" + word + ">"
			var keywordClose = "</" + word + ">"

			if (str.indexOf(keyword) >= 0) {
				var arr = str.split(keyword);
				res.push(arr[0]);
				for (var i = 1; i < arr.length; i++) {
					var arr1 = arr[i].split(keywordClose);
					res.push(changeCase(arr1[0], word));
					res.push(arr1[1]);
				}

				res = (res.length > 0 ? res.join("") : "")
			}
			else {
				res = str;
			}

			return res;
		}

		function changeCase(str, word) {
			var res;

			switch (word) {
				case "upcase":
					res = str.toUpperCase();
					break;
				case "lowcase":
					res = str.toLowerCase();
					break;
				case "mixcase":
					res = str.toMixCase()
					break;
				default:
					res = str;
					break;
			}

			return res;
		}

		// Button OnClick
		function doChange(){
			// Read User input
			var input = jsConsole.read("#input");

			// Output
			jsConsole.writeLine("You have entered:");
			jsConsole.writeLine("<blockquote>" + input.htmlEscape() + "</blockquote>");

			// Do the change
			var result = changeText(input);
			jsConsole.writeLine("Result:");
			jsConsole.writeLine("<blockquote>" + result.htmlEscape() + "</blockquote>");
		}
	</script>
</body>
</html>
